package com.a3dweijing.wetouch2.Activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.EvenBusUtil;
import com.a3dweijing.wetouch2.Util.FileUtil;
import com.a3dweijing.wetouch2.Util.GlideUtil;
import com.a3dweijing.wetouch2.Util.PermissionapplicationHelp;
import com.a3dweijing.wetouch2.Util.ProgressDialogHelp;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.EvenMsg;
import com.a3dweijing.wetouch2.bean.Headmsg;
import com.a3dweijing.wetouch2.bean.User;
import com.a3dweijing.wetouch2.constant.Api;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.a3dweijing.wetouch2.network.RetrofitUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TException;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.a3dweijing.wetouch2.Activity.ResetNicknameActivity.RESETNICKNAMEACTIVITYCODE;
import static com.a3dweijing.wetouch2.Util.FileUtil.CACHE_DIR;
import static com.a3dweijing.wetouch2.Util.FileUtil.shearshead;

public class SettingActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener
{

    @BindView(R.id.back)
    ImageView back;

    @BindView(R.id.top_text)
    TextView topText;

    @BindView(R.id.top_right)
    TextView topRight;

    @BindView(R.id.top_all)
    RelativeLayout topAll;

    @BindView(R.id.head_Img)
    ImageView headImg;

    @BindView(R.id.resetHeadImg)
    RelativeLayout resetHeadImg;

    @BindView(R.id.resetNickname)
    RelativeLayout resetNickname;

    @BindView(R.id.MyInvite)
    RelativeLayout MyInvite;

    @BindView(R.id.MyInviteList)
    RelativeLayout MyInviteList;

    @BindView(R.id.bindCard)
    RelativeLayout bindCard;

    @BindView(R.id.clearC)
    RelativeLayout clearC;

    @BindView(R.id.outU)
    RelativeLayout outU;

    @BindView(R.id.nickname)
    TextView nickname;

    private InvokeParam invokeParam;

    private ProgressDialog dialog;

    private TakePhoto takePhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        takePhoto.onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);

        initView();
    }

    private void initView()
    {
        dialog = ProgressDialogHelp.create(this, "提示", "正在提交中", false);
        User user = Singleton.getInstance().getUser();
        topText.setText("设置");
        nickname.setText(user.getUser_name());
        String url = GlideUtil.getInstance().checkUrl(user.getUser_head());
        GlideUtil.getInstance().showByCircle(SettingActivity.this, url, headImg);

    }

    @OnClick({R.id.back, R.id.resetHeadImg, R.id.resetNickname, R.id.MyInvite, R.id.MyInviteList, R.id.bindCard,
            R.id.clearC, R.id.outU})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.resetHeadImg:
                selectPicture();
                break;
            case R.id.resetNickname:
                Intent intent_reNickname = new Intent(SettingActivity.this, ResetNicknameActivity.class);
                startActivityForResult(intent_reNickname, RESETNICKNAMEACTIVITYCODE);
                break;
            case R.id.MyInvite:
                Intent myInviteINtent = new Intent(SettingActivity.this, MyInviteActivity.class);
                startActivity(myInviteINtent);
                break;
            case R.id.MyInviteList:
                Intent intent_invitList = new Intent(SettingActivity.this,InviteListActivity.class);
                startActivity(intent_invitList);
                break;
            case R.id.bindCard:
                Intent myInviteList = new Intent(this, CardListActivity.class);
                startActivity(myInviteList);
                break;
            case R.id.clearC:
                break;
            case R.id.outU:
                Intent intent = new Intent(this, LoginActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
        }
    }

    private static String[] PERMISSIONS_STORAGE =
            {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};

    private void selectPicture() {
        int permissionapplication = PermissionapplicationHelp
                .Permissionapplication(this, "android.permission.WRITE_EXTERNAL_STORAGE", PERMISSIONS_STORAGE);
        if (permissionapplication == PERMISSION_GRANTED) {
            photpicker();
        } else {
            Toast.makeText(this, "无使用权限,请同意该权限", Toast.LENGTH_SHORT).show();
        }
    }

    private void photpicker() {
        PhotoPicker.builder().setPhotoCount(1).setShowCamera(true).setShowGif(true).setPreviewEnabled(true).start(this,
                PhotoPicker.REQUEST_CODE);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        takePhoto.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        takePhoto.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE)
        {
            if (data != null)
            {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                CropOptions cropOptions =
                    new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();
                try
                {
                    Uri parse = FileUtil.getUri();
                    takePhoto.onCrop(Uri.fromFile(new File(photos.get(0))), parse, cropOptions);
                }
                catch (TException e)
                {
                    e.printStackTrace();
                }
            }
        } else if (resultCode == RESULT_OK && requestCode == RESETNICKNAMEACTIVITYCODE) {
            nickname.setText(Singleton.getInstance().getUser().getUser_name());
            EvenMsg evenMsg = new EvenMsg(EvenMsg.RESETNICKNAMEACTIVITYRESTNAME,null);
            EvenBusUtil.post(evenMsg);
        }
    }

    @Override
    public void takeSuccess(TResult result)
    {
        dialog.show();
        Api api = RetrofitUtil.getInstance().getApi();
        // 构建要上传的文件
        File e = new File(CACHE_DIR + shearshead);
        MultipartBody.Part body = RetrofitUtil.getInstance().getBodyByFile("headFile", e);
        User user = Singleton.getInstance().getUser();
        String userId = user.getUser_id();
        MultipartBody.Part no1 = RetrofitUtil.getInstance().getBodyByDate("user_id", userId);
        String url = GlideUtil.getInstance().checkUrl(user.getUser_head());
        MultipartBody.Part no2 = RetrofitUtil.getInstance().getBodyByDate("user_head", url);
        Call<JsonObject> call = api.updatehead(body, no1, no2);
        call.enqueue(new Callback<JsonObject>()
        {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response)
            {
                JsonObject s = response.body();
                Gson gson = new Gson();
                Headmsg headmsg = gson.fromJson(s, Headmsg.class);
                if (headmsg.isFlag())
                {
                    String userHead = headmsg.getUserHead();
                    Singleton.getInstance().getUser().setUser_head(userHead);
                    String s1 = GlideUtil.getInstance().checkUrl(userHead);
                    GlideUtil.getInstance().showByCircle(SettingActivity.this, s1, headImg);
                }
                Toast.makeText(SettingActivity.this, headmsg.getMsg(), Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t)
            {
                Toast.makeText(SettingActivity.this, "服务器访问失败", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
    }

    @Override
    public void takeFail(TResult result, String msg)
    {

    }



    @Override
    public void takeCancel()
    {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam)
    {
        PermissionManager.TPermissionType type =
            PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type))
        {
            this.invokeParam = invokeParam;
        }
        return type;
    }
}
